package com.mf.ergate.web.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mf.ergate.web.security.captcha.CaptchaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码控制器
 * User: zhaoming
 * DateTime: 2017-11-06
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 获取验证码图片
     */
    @RequestMapping(value = "/getImage", method = RequestMethod.GET)
    public ModelAndView getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/png");

        String captchaText = defaultKaptcha.createText();
        CaptchaUtils.setCaptchaValue(request, captchaText);

        BufferedImage bi = defaultKaptcha.createImage(captchaText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "png", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 校验验证码
     */
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    @ResponseBody
    public boolean check(HttpServletRequest request) {
        boolean flag = false;
        String captchaValue = request.getParameter("captcha");
        if (captchaValue != null && captchaValue.equalsIgnoreCase(CaptchaUtils.getCaptchaValue(request))) {
            flag = true;
        }
        return flag;
    }

    /**
     * 校验验证码
     */
    @RequestMapping(value = "/session", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> session(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("session - KAPTCHA_SESSION_KEY", request.getSession().getAttribute("KAPTCHA_SESSION_KEY") + "");
        map.put("session - SESSION_CAPTCHA_KEY", request.getSession().getAttribute("SESSION_CAPTCHA_KEY") + "");
        return map;
    }
}
